package com.qmth.gkwb.data.system;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.qmth.gkwb.data.document.Settings;
import com.qmth.gkwb.data.document.TimeConfig;
import com.qmth.gkwb.data.entity.DictCity;
import com.qmth.gkwb.data.repository.DictCityRepo;
import com.qmth.gkwb.data.repository.SettingRepo;

/**
 * 系统设置
 * @author zhengmin
 *
 */
@Service
public class SettingService {

	@Autowired private SettingRepo settingRepo;
	@Autowired private DictCityRepo cityRepo;
	
	@Autowired private Environment evn;
	
	@Transactional
	public Settings getSettings(){
		Settings settings = null;
		List<Settings> list = settingRepo.findAll();
		if(list.size() == 0){
			//新建设置
			settings = new Settings();
			settings.setYear(evn.getProperty("app.year"));
			settings.setSystemEnabled(true);
			Calendar cal = Calendar.getInstance();
			List<DictCity> dictCities = cityRepo.findByProvId(42, new Sort("no"));
			for(DictCity c : dictCities){
				TimeConfig config = new TimeConfig(c.getName(),c.getNo(),true,cal.getTime(),cal.getTime());
				settings.addCity(config);
			}
			settingRepo.save(settings);
		}
		else{
			settings = list.get(0);
		}
		return settings;
	}
	
	@Transactional
	public Settings saveSettings(Settings settings){
		SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat to = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		try{
			if(settings.getSystemStartTime() != null){
				String sysStart = from.format(settings.getSystemStartTime());
				Date start = to.parse(sysStart+" 00:00:00");
				settings.setSystemStartTime(start);
			}
			if(settings.getSystemEndTime() != null){
				String sysEnd = from.format(settings.getSystemEndTime());
				Date end = to.parse(sysEnd+" 00:00:00");
				settings.setSystemEndTime(end);
			}
			for(TimeConfig config : settings.getCities()){
				String time = from.format(config.getStart());
				Date date = to.parse(time+" 00:00:00");
				config.setStart(date);
				String endTime = from.format(config.getEnd());
				Date dateEnd = to.parse(endTime+" 00:00:00");
				config.setEnd(dateEnd);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return settingRepo.save(settings);
	}
	
	public TimeConfig getCityTime(String cityNo,Settings settings){
		TimeConfig date = null;
		for(TimeConfig config :settings.getCities()){
			if(config.getKey().equals(cityNo)){
				date = config;
			}
		}
		return date;
	}
}
